/*
 * Copyright (c) 2021-2031, 河北计全科技有限公司 (https://www.jeequan.com & jeequan@126.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.splic.product.service.impl.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.splic.common.config.AliPayConfig;
import com.splic.common.enums.OrderStatusEnum;
import com.splic.common.exception.BusinessException;
import com.splic.common.utils.StringUtils;
import com.splic.product.domain.Order;
import com.splic.product.domain.Product;
import com.splic.product.service.OrderService;
import com.splic.product.service.PayNotifyService;
import com.splic.product.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.MutablePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

import static com.alipay.api.AlipayConstants.CHARSET_UTF8;
import static com.alipay.api.AlipayConstants.SIGN_TYPE_RSA2;

/*
* 支付宝 回调接口实现类
*
* @author terrfly
* @site https://www.jeequan.com
* @date 2021/6/8 17:20
*/
@Service
@Slf4j
public class AlipayNotifyService extends AbstractNotifyService{

    @Autowired
    private OrderService orderServiceImpl;

    @Autowired
    private ProductService productServiceImpl;

    @Override
    public MutablePair<String, Object> parseParams(HttpServletRequest request, PayNotifyService.NoticeTypeEnum noticeTypeEnum) {

        try {
            log.info("==============开始获取alipay的入参");
            JSONObject params = getReqParamJSON();
            String orderNo = params.getString("out_trade_no");
            log.info("==============结束获取alipay的入参,订单号:{},参数:{}",orderNo, JSONObject.toJSONString(params));
            return MutablePair.of(orderNo, params);

        } catch (Exception e) {
            log.error("error", e);
            throw new BusinessException("fail");
        }
    }



    @Override
    public void doNotice(HttpServletRequest request, Object params, Order order, PayNotifyService.NoticeTypeEnum noticeTypeEnum) throws AlipayApiException {

        Map<String,String> jsonParams = (Map<String,String>) params;


        Product product = productServiceImpl.selectProductById(order.getProductId());
        if (product == null){
            throw new BusinessException("应用获取失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(product.getAlipayConfig());

        //移除回调链接上面的系统携带的参数payType
//        jsonParams.remove("payType");
        boolean verifyResult = AlipaySignature.rsaCheckV1(jsonParams,jsonObject.getString("alipay_public_key"),CHARSET_UTF8, SIGN_TYPE_RSA2);
        log.info("verifyResult:{}",verifyResult);

        //验签失败
        if(!verifyResult){
            log.error("验签失败");
            throw new BusinessException("验签失败");
        }

        BigDecimal amount = new BigDecimal(jsonParams.get("total_amount"));
        if(amount.compareTo(order.getAmount()) != 0){
            throw new BusinessException("订单对应金额不匹配");
        }
        if(!StringUtils.equals(jsonParams.get("seller_id"),jsonObject.getString("pid"))){
            throw new BusinessException("操作方不匹配");
        }
        //验签成功后判断上游订单状态
        if(!StringUtils.equals("TRADE_SUCCESS",jsonParams.get("trade_status"))){
            throw new BusinessException("订单支付状态不是成功状态");
        }
        order.setStatus(OrderStatusEnum.PAY_SUCCESS.getCode());
        orderServiceImpl.updateOrderStatus(order);
    }





}
